package com.yh.ldzl.controller;

import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.api.InventoryService;
import com.yh.ldzl.domain.QcOqcLine;
import com.yh.ldzl.service.IQcOqcLineService;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.yh.ldzl.domain.QcOqc;
import com.yh.ldzl.service.IQcOqcService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 出货检验单Controller
 * 
 * @author yanghuai
 * @date 2025-07-13
 */
@RestController
@RequestMapping("/oqc")
public class QcOqcController extends BaseController
{
    @Autowired
    private IQcOqcService qcOqcService;
    @Autowired
    private IQcOqcLineService qcOqcLineService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Resource
    private InventoryService inventoryService;

    // 消息类型常量，应与RecordActionController中的常量保持一致
    private static final String MESSAGE_TYPE_HEADER = "message_type";
    private static final String MESSAGE_TYPE_QC_OQC = "qc_oqc";
    /**
     * 查询出货检验单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(QcOqc qcOqc)
    {
        startPage();
        List<QcOqc> list = qcOqcService.selectQcOqcList(qcOqc);
        return getDataTable(list);
    }

    /**
     * 导出出货检验单列表
     */
    @Log(title = "出货检验单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QcOqc qcOqc)
    {
        List<QcOqc> list = qcOqcService.selectQcOqcList(qcOqc);
        ExcelUtil<QcOqc> util = new ExcelUtil<QcOqc>(QcOqc.class);
        util.exportExcel(response, list, "出货检验单数据");
    }

    /**
     * 获取出货检验单详细信息
     */
    @GetMapping(value = "/{oqcId}")
    public AjaxResult getInfo(@PathVariable("oqcId") Long oqcId)
    {
        return success(qcOqcService.selectQcOqcByOqcId(oqcId));
    }

    /**
     * 新增出货检验单
     */
    @Log(title = "出货检验单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody QcOqc qcOqc)
    {
        System.out.println("准备新增QC检测单");
        try {
            System.out.println("准备插入数据");
            int result = qcOqcService.insertQcOqc(qcOqc);
            System.out.println("oqcId:" + qcOqc.getOqcId() + ", 新增QC检测单成功");
            if (result <= 0) {
                return AjaxResult.error("新增QC检测单失败");
            }

            Long oqcId = qcOqc.getOqcId();
            System.out.println("oqcId:" + oqcId + ", 准备发送消息");

            // 创建消息关联ID，便于跟踪消息
            String correlationId = "qc-oqc-" + oqcId + "-" + System.currentTimeMillis();
            CorrelationData correlationData = new CorrelationData(correlationId);

            // 创建消息头部，设置消息类型
            org.springframework.amqp.core.MessagePostProcessor messagePostProcessor = message -> {
                MessageProperties properties = message.getMessageProperties();
                properties.setHeader(MESSAGE_TYPE_HEADER, MESSAGE_TYPE_QC_OQC);
                return message;
            };

            // 发送消息，并使用correlationData跟踪，附加消息类型
            rabbitTemplate.convertAndSend(
                    "myExchange",
                    "myRoutingKey",
                    qcOqc,
                    messagePostProcessor,
                    correlationData
            );

            System.out.println("oqcId:" + oqcId + ", 消息已发送, correlationId: " + correlationId + ", messageType: " + MESSAGE_TYPE_QC_OQC);

            return AjaxResult.success("新增QC检测单成功，消息已发送");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送消息异常: " + e.getMessage());
            return AjaxResult.error("操作异常: " + e.getMessage());
        }

    }

    /**
     * 修改出货检验单
     */
    @Log(title = "出货检验单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody QcOqc qcOqc)
    {
        return toAjax(qcOqcService.updateQcOqc(qcOqc));
    }

    /**
     * 删除出货检验单
     */

    @Log(title = "出货检验单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{oqcIds}")
    public AjaxResult remove(@PathVariable Long[] oqcIds)
    {
        return toAjax(qcOqcService.deleteQcOqcByOqcIds(oqcIds));
    }


    /**
     * 分页查询检验单行信息
     * @param qcOqcLine 请求参数，包含查询条件
     * @return TableDataInfo 分页查询结果
     */
    @PostMapping("/selectQcOqcLineList")
    public TableDataInfo list(@RequestBody  QcOqcLine qcOqcLine)
    {
        startPage();
        List<QcOqcLine> list = qcOqcLineService.selectQcOqcLineList(qcOqcLine);
        return getDataTable(list);
    }
    /**
     * 根据检验单行ID查询检验单行详细信息
     * @param oqcId 路径参数，检验单行ID
     * @return QcOqcLine 检验单行详细信息
     */
    @GetMapping("/selectQcOqcLineByLineId/{oqcId}")
    public QcOqcLine getQcOqcLineInfo(@PathVariable("lineId") Long oqcId)
    {
        return qcOqcLineService.selectQcOqcLineByLineId(oqcId);
    }

    /**
     * 新增检验单行信息
     * @param qcOqcLine 请求参数，包含新增数据
     * @return AjaxResult 操作结果
     */
    @Log(title = "检验单行", businessType = BusinessType.INSERT)
    @PostMapping("/addQcOqcLine")
    public AjaxResult add(@RequestBody QcOqcLine qcOqcLine)
    {
        return toAjax(qcOqcLineService.insertQcOqcLine(qcOqcLine));


    }
    /**
     * 更新检验单行信息
     * @param qcOqcLine 请求参数，包含更新数据
     * @return AjaxResult 操作结果
     */
    @Log(title = "检验单行", businessType = BusinessType.UPDATE)
    @PutMapping("/updateQcOqcLine")
    public AjaxResult edit(@RequestBody QcOqcLine qcOqcLine)
    {
        return toAjax(qcOqcLineService.updateQcOqcLine(qcOqcLine));
    }
    /**
     * 删除指定ID的检验单行信息
     * @param lineIds 路径参数，包含要删除的检验单行IDs
     * @return AjaxResult 操作结果
     */
    @Log(title = "检验单行", businessType = BusinessType.DELETE)
    @DeleteMapping("deleteQcOqcLineByLineIds/{lineIds}")
    public AjaxResult deleteQcOqcLineByLineIds(@PathVariable Long[] lineIds)
    {
        return toAjax(qcOqcLineService.deleteQcOqcLineByLineIds(lineIds));
    }

    /**
     * 兼容InventoryService接口的待检测销售出货订单查询
     * 使用GET请求和路径变量格式
     */
    @GetMapping("/outbound/selectCkProductSales/{sales_code}/{sales_name}")
    public TableDataInfo selectCkProductSalesCompat(@PathVariable(value = "sales_code", required = false) String sales_code,
                                              @PathVariable(value = "sales_name", required = false) String sales_name){
       return inventoryService.selectCkProductSales(sales_code,sales_name);
    }

    /**
     * 为兼容前端GET请求+参数方式，增加一个转发方法
     */
    @GetMapping("/outbound/selectCkProductSales")
    public TableDataInfo selectCkProductSalesGet(@RequestParam(value = "sales_code", required = false) String sales_code,
                                              @RequestParam(value = "sales_name", required = false) String sales_name) {
        // 处理可能的null值，Feign不允许路径变量为null或空字符串
        // 使用占位符"%"代替空值，确保URL路径正确（避免使用"_"作为通配符）
        String code = (sales_code == null || sales_code.isEmpty()) ? "%" : sales_code;
        String name = (sales_name == null || sales_name.isEmpty()) ? "%" : sales_name;
        return selectCkProductSalesCompat(code, name);
    }


}
